package tcp

import (
	"context"
	"core/id"
	getty "github.com/apache/dubbo-getty"
	"github.com/dubbogo/gost/log/logger"
	"iotall/iotcore/api/proxyup"
	"iotall/iotproxy/pkg"
	"iotall/iotproxy/proxyconfig"
	"iotall/iotproxy/server/dataserver"

	"time"
)

type MsgHandler struct {
	Server *TcpServer
}

func (h *MsgHandler) OnOpen(session getty.Session) error {
	session.SetAttribute("Sid", "")
	session.SetAttribute("LstRev", time.Now())
	session.SetAttribute("CrtDt", time.Now())
	//考虑黑名单
	return nil
}

func (h *MsgHandler) OnError(session getty.Session, err error) {

	return
}

func (h *MsgHandler) OnClose(session getty.Session) {
	var Sid = session.GetAttribute("Sid").(string)
	if Sid == "" {
		var CrtDt = session.GetAttribute("CrtDt").(time.Time)
		dataserver.ConnectInfoServer.Add(id.NewId(), h.Server.CommPort.Id, Sid, session.RemoteAddr(), "连接", CrtDt)
	}
	dataserver.ConnectInfoServer.Add(id.NewId(), h.Server.CommPort.Id, Sid, session.RemoteAddr(), "断开", time.Now())

	var in = &proxyup.CloseReq{
		Sid:         Sid,
		RemoteAddr:  session.RemoteAddr(),
		CommPortId:  h.Server.CommPort.Id,
		CommProxyId: proxyconfig.Config.Id,
	}
	var _, err = pkg.ProxyUpClientImpl.Close(context.Background(), in)
	if err != nil {
		logger.Errorf("OnClose %v", err)
	}

	return
}

func (h *MsgHandler) OnMessage(session getty.Session, pkgdata interface{}) {

	return
}

func (h *MsgHandler) OnCron(session getty.Session) {

	var LstRev = session.GetAttribute("LstRev").(time.Time)
	var d = time.Since(LstRev)
	if d > time.Second*time.Duration(h.Server.CommPort.Timeout) {
		//fmt.Println("force clsoe")
		session.Close()
	}
	return
}
